﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using eDoctor.SDK.WeChat.Response;
using Models;

namespace Web.Areas.Admin.Lib
{
    public class Site : siteLogic
    {
        /// <summary>
        /// 获取约定好的token
        /// </summary>
        /// <returns></returns>
        public string GetToken()
        {
            var dt = this.db.ExecuteDataTableSql("select token from site;");
            if (dt.Rows.Count < 1) return string.Empty;
            else return dt.Rows[0][0].ToString();
        }

        /// <summary>
        /// 获取项目accesstoken
        /// </summary>
        /// <returns></returns>
        public string GetAccessToken()
        {
            var dt = base.db.ExecuteDataTableSql("select accesstoken,expiredtime,appid,appsecret from dbo.site ;");
            //判断项目是否存在
            if (dt.Rows.Count < 1) return null;
            //判断acesstooken是否存在和判断expiredtime是否过期
            if (string.IsNullOrEmpty(dt.Rows[0][0].ToString()) || string.IsNullOrEmpty(dt.Rows[0][1].ToString()) || DateTime.Parse(dt.Rows[0][1].ToString()).CompareTo(DateTime.Now) < 0)
            {
                string appid = dt.Rows[0][2].ToString(), appsecret = dt.Rows[0][3].ToString();
                //获取微信授权access_token
                var t = eDoctor.SDK.WeChat.Call.GetToken(appid, appsecret);
                if (t == null || string.IsNullOrEmpty(t.access_token))
                {
                    if (t != null)
                    {
                        //todo: get accesstoken error
                    };
                    return null;
                }
                //更新数据库中access_token
                this.UpdateAccessToken(t.access_token, t.expires_in);
                return t.access_token;
            }
            //返回有效acesstooken
            return dt.Rows[0][0].ToString();
        }

        /// <summary>
        /// 更新项目accesstoken
        /// </summary>
        /// <param name="accesstoken"></param>
        /// <returns></returns>
        internal Boolean UpdateAccessToken(string accesstoken, long expires_in)
        {
            return base.db.ExecuteNonQuerySql("update site set accesstoken=@accesstoken,expiredtime=@expiredtime;",
            new List<System.Data.Common.DbParameter>()
            {
                new System.Data.SqlClient.SqlParameter("@accesstoken",accesstoken){SqlDbType=System.Data.SqlDbType.NVarChar},
                //设置过期时间，提前5分钟
                new System.Data.SqlClient.SqlParameter("@expiredtime",DateTime.Now.AddSeconds(expires_in-300)){SqlDbType=System.Data.SqlDbType.DateTime},
            }) > 0;
        }

        /// <summary>
        /// 获取微信关注自动回复素材ID
        /// </summary>
        /// <returns></returns>
        public int GetSubScribeReplyId(out string content)
        {
            var dt = this.db.ExecuteDataTableSql("select subscribereplyid,subscribecontent from site;");
            content = null;
            if (dt.Rows.Count < 1) return 0;
            content = dt.Rows[0][1].ToString();
            return int.Parse(dt.Rows[0][0].ToString());
        }

        /// <summary>
        /// 获取微信默认回复素材id
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public int GetDefaultReplyId(out string content)
        {
            var dt = this.db.ExecuteDataTableSql("select defaultreplyid,defaultcontent from site;");
            content = null;
            if (dt.Rows.Count < 1) return 0;
            content = dt.Rows[0][1].ToString();
            return int.Parse(dt.Rows[0][0].ToString());
        }

        public bool GetAppConfig(out string appid, out string appsecret)
        {
            var dt = this.db.ExecuteDataTableSql("select appid,appsecret from site;");

            appid = dt.Rows[0][0].ToString();
            appsecret = dt.Rows[0][1].ToString();

            return true;
        }

        /// <summary>
        /// 获取jsapi_ticket
        /// </summary>
        /// <returns></returns>
        public string GetTicket()
        {
            var dt = base.db.ExecuteDataTableSql("select ticket,ticketexpiredtime from dbo.site;");
            //判断项目是否存在
            if (dt.Rows.Count < 1) return null;
            //判断acesstooken是否存在和判断expiredtime是否过期
            if (string.IsNullOrEmpty(dt.Rows[0][0].ToString()) || string.IsNullOrEmpty(dt.Rows[0][1].ToString()) || DateTime.Parse(dt.Rows[0][1].ToString()).CompareTo(DateTime.Now) < 0)
            {
                //获取本项目的access_token
                var access_token = this.GetAccessToken();
                //获取jsapi_ticket是公众号用于调用微信JS接口的临时票据
                var t = new eDoctor.SDK.WeChat.Call(access_token).GetTicket();

                if (t == null || t.ticket == null) return null;

                //更新数据库中ticket
                this.UpdateTicket(t.ticket, t.expires_in);
                return t.ticket;
            }
            //返回有效acesstooken
            return dt.Rows[0][0].ToString();
        }

        /// <summary>
        /// 更新项目ticket
        /// </summary>
        /// <param name="ticket"></param>
        /// <returns></returns>
        internal Boolean UpdateTicket(string ticket, long expires_in)
        {
            return base.db.ExecuteNonQuerySql("update site set [ticket]=@ticket,ticketexpiredtime=@ticketexpiredtime;",
            new List<System.Data.Common.DbParameter>()
            {
                new System.Data.SqlClient.SqlParameter("@ticket",ticket){SqlDbType=System.Data.SqlDbType.NVarChar},
                //设置过期时间，提前30分种
                new System.Data.SqlClient.SqlParameter("@ticketexpiredtime",DateTime.Now.AddSeconds(expires_in-1800)){SqlDbType=System.Data.SqlDbType.DateTime},
            }) > 0;
        }
    }
}